#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time: 2023/6/16 11:53
# @Author: Anthony (anthony66888@163.com)
# @description: 
"""
import random
import time
from urllib import parse

import requests

from auto_battle_room import YamlControl


class UserInfo:
    def __init__(self):
        """初始化登陆后台"""
        self.config_data = YamlControl("/data/config.yaml").read_yaml()
        self.host = self.config_data["admin_host"]  # 生产环境
        self.token = self.config_data["admin_token"]  # 后台token

    def get_sms_code(self):
        """获取短信验证码"""
        url = "/api/sys/user/smsCode"
        data = {
            "phone": "13999999999"
        }
        requests.get(url=self.host + url, params=data)

    def get_uid(self, phone):
        """获取用户ID"""
        url = "/api/sys/user/customer/page"
        data = {
            "phone": phone,
            "totalCount": 1,
            "page": 1,
            "pageSize": 10
        }
        headers = {
            "Token": self.token,
            "Currentroleid": "7"
        }
        response = requests.get(url=self.host + url, params=data, headers=headers)
        return response.json()["data"]["pageData"][0]["id"]

    def get_user_info(self, uid):
        """
        获取用户当前余额
        :param uid: 用户ID
        :return: 用户当前余额
        """
        url = "/api/sys/user/customer/userInfo"
        data = {
            "id": uid
        }
        headers = {
            "Token": self.token,
            "Currentroleid": "7"
        }
        response = requests.get(url=self.host + url, params=data, headers=headers)
        # balance = - response.json()["data"]["balance"]
        # return balance
        return response.json()["data"]

    def add_user(self, phone):
        """后台单次新增用户"""
        url = "/api/sys/user/customer/addCustomer"
        data = {
            "key": phone,
            "password": phone,
            "confirmPassword": phone,
            "customerType": 2,
            "remark": "自动任务用户"
        }
        data = parse.urlencode(data)
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Token": self.token,
            "Currentroleid": "7"
        }
        requests.post(url=self.host + url, data=data, headers=headers)
        # response = requests.post(url=self.host + url, data=data, headers=headers)
        # print(response.text)

    def add_balance(self, uid):
        """后台单次给用户充值"""
        # value = random.choice([random.randint(400, 499),
        #                        random.randint(1000, 1999),
        #                        random.randint(3000, 4999),
        #                        random.randint(5000, 9999)
        #                        ])
        # random_int = random.randint(1, 4)
        # if random_int == 1:
        #     value = random.randint(1000, 1999)
        # else:
        #     value = random.randint(100, 500)
        user_info = self.get_user_info(uid)
        # user_balance = user_info["balance"]
        grade = user_info["grade"]
        experience = user_info["experience"]

        value = random.randint(100, 500)

        if float(experience) + value > 19999:
            grade_list = [4, 5]
            experience_list = [5100, 10100]
            grade = random.choice(grade_list)
            grade_index = grade_list.index(grade)
            experience = str(experience_list[grade_index])
            # self.clear_balance(uid, grade, experience)
        url = "/api/sys/user/customer/modifyLevelAndBalance"
        data = {
            "id": uid,
            # "initBalance": 0.00,
            "balance": value,
            "changeBalance": value,
            "grade": grade,
            "experience": experience
        }
        data = parse.urlencode(data)
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Token": self.token,
            "Currentroleid": "7"
        }
        requests.post(url=self.host + url, data=data, headers=headers)
        # response = requests.post(url=self.host + url, data=data, headers=headers)
        # print(response.text)

    def clear_balance(self, uid, grade, experience):
        """后台单次清空用户余额"""
        balance = self.get_user_info(uid)["balance"]
        url = "/api/sys/user/customer/modifyLevelAndBalance"
        # grade = random.randint(2, 3)
        # experience = [1200, 2300][grade - 2]
        data = {
            "id": uid,
            # "initBalance": 0.00,
            "balance": - balance + 1,
            "changeBalance": - balance + 1,
            "grade": grade,
            "experience": experience
        }
        data = parse.urlencode(data)
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Token": self.token,
            "Currentroleid": "7"
        }
        requests.post(url=self.host + url, data=data, headers=headers)
        # response = requests.post(url=self.host + url, data=data, headers=headers)
        # print(response.text)

    def create_many_user(self, phone1, phone2):
        """
        后台批量新增用户
        :param phone1: 第一位用户手机号
        :param phone2: 最后一位手机号
        """
        for phone in range(phone1, phone2+1):
            self.add_user(phone)


def batch_add_balance(phone1, phone2=None):
    """
    后台批量给用户充值
    :param phone1: 第一个用户手机号
    :param phone2: 最后一个手机号，如果为空则只给第一个用户充值
    """
    user_info = UserInfo()
    print("开始充值")
    i = 0
    if phone2 is None:
        print(f"开始给{phone1}充值")
        try:
            uid = user_info.get_uid(phone1)
            # user_info.clear_balance(uid)
            user_info.add_balance(uid)
            print(f"给{phone1}充值完毕")
        except Exception as e:
            print(f"用户{phone2}充值失败，错误信息:/t{e}")
    else:
        for phone in range(phone1, phone2+1):
            try:
                uid = user_info.get_uid(phone)
                # user_info.clear_balance(uid)  # 先清空用户余额
                user_info.add_balance(uid)  # 再添加用户余额
                i += 1
                if i % 10 == 0:
                    print(f"已充值{i}个用户")
                    time.sleep(1)
            except Exception as e:
                print(f"用户{phone}充值失败，错误信息:/t{e}")
                continue
        print("全部充值完毕")


if __name__ == '__main__':
    # # 测试环境d
    p1 = 26111111110
    p2 = 26111111799
    batch_add_balance(p1, p2)

    # p1 = 26111111798
    # batch_add_balance(p1)

    # 生产环境
    # p1 = 0
    # p2 = 0
    # for i in range(2):
    #     if i == 0:
    #         p1 = 26111111110
    #         p2 = 26111111399
    #     elif i == 1:
    #         p1 = 26111111900
    #         p2 = 26111111949
    #
    #     batch_add_balance(p1, p2)

